﻿#define _CRT_SECURE_NO_WARNINGS 1
#include "Seqlist.h"

//判断顺序表的内存是否够用
void SLCheckCapacity(SL* ps)
{
	//如果空间小于等于有效个数，则按二倍扩展（初始0则扩为4）
	if (ps->capacity <= ps->size)
	{
		int newcap = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		Type* tmp = (Type*)realloc(ps->arr, sizeof(Type) * newcap);
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newcap;
	}
}
//顺序表初始化
void SLInit(SL* ps)
{
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

//顺序表的销毁
void SLDestroy(SL* ps)
{
	if (ps->arr)
	{
		free(ps->arr);
	}
	ps->arr = NULL;
	ps->size = ps->capacity = 0;
}

//头部插入
void SLPushHead(SL* ps, Type x)
{
	assert(ps);
	SLCheckCapacity(ps);//判断空间大小
	//将后面的数据往后移动(从后面开始移动)
	for (int i = ps->size; i > 0; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[0] = x;
	ps->size++;
}

//头部删除
void SLPopHead(SL* ps)
{
	assert(ps);
	assert(ps->size > 0);
	//往前移动（从前开始）
	for (int i = 0; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//尾部插入
void SLPushEnd(SL* ps, Type x)
{
	assert(ps);
	SLCheckCapacity(ps);//判断空间大小
	ps->arr[ps->size] = x;
	ps->size++;
}

//尾部删除
void SLPopEnd(SL* ps)
{
	assert(ps);
	ps->size--;
}
//
//顺序表的指定位置插入
void SLInsert(SL* ps, int pos, Type x)
{
	assert(ps);
	SLCheckCapacity(ps);
	assert(pos >= 0 && pos <= ps->size);
	// 插入位置的数往后移
	for (int i = ps->size; i > pos; i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	ps->size++;
}
//指定位置删除
void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	//往前移动，并覆盖
	for (int i = pos; i < ps->size - 1; i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	ps->size--;
}

//顺序表的指定位置的修改
void SLAlter(SL* ps, int pos, Type x)
{
	assert(ps);
	assert(pos >= 0 && pos < ps->size);
	ps->arr[pos] = x;
}

////顺序表查找数据
//int SLFind(SL* ps, Type x)
//{
//	for (int i = 0; i < ps->size; i++)
//	{
//		if (ps->arr[i] == x)
//		{
//			return i;
//		}
//	}
//	return -1;
//}
//
////顺序表的打印（int类型）便于观察
//void SLprint(SL* ps)
//{
//	for (int i = 0; i < ps->size; i++)
//	{
//		printf("%d ", ps->arr[i]);
//	}
//	printf("\n");
//}
